<template>
  <div :class="prefixCls" :style="{ width: containerWidth }">
    <ImgUpload
      :fullscreen="fullscreen"
      :max-count="1"
      @uploading="handleImageUploading"
      @done="handleDone"
      v-if="showImageUpload"
      v-show="editorRef"
      :disabled="disabled"
    />
    <textarea
      :id="tinymceId"
      ref="elRef"
      :style="{ visibility: 'hidden' }"
      v-if="!initOptions.inline"
    ></textarea>
    <slot v-else></slot>
  </div>
</template>

<script lang="ts">
  import type { Editor, RawEditorSettings } from 'tinymce';
  import tinymce from 'tinymce/tinymce';
  import 'tinymce/themes/silver';
  import 'tinymce/icons/default/icons';
  import 'tinymce/plugins/advlist';
  import 'tinymce/plugins/anchor';
  import 'tinymce/plugins/autolink';
  import 'tinymce/plugins/autosave';
  import 'tinymce/plugins/code';
  import 'tinymce/plugins/codesample';
  import 'tinymce/plugins/directionality';
  import 'tinymce/plugins/fullscreen';
  import 'tinymce/plugins/hr';
  import 'tinymce/plugins/insertdatetime';
  import 'tinymce/plugins/link';
  import 'tinymce/plugins/lists';
  import 'tinymce/plugins/media';
  import 'tinymce/plugins/image';
  import 'tinymce/plugins/imagetools';
  import 'tinymce/plugins/nonbreaking';
  import 'tinymce/plugins/noneditable';
  import 'tinymce/plugins/pagebreak';
  import 'tinymce/plugins/paste';
  import 'tinymce/plugins/preview';
  import 'tinymce/plugins/print';
  import 'tinymce/plugins/save';
  import 'tinymce/plugins/searchreplace';
  import 'tinymce/plugins/spellchecker';
  import 'tinymce/plugins/tabfocus';
  // import 'tinymce/plugins/table';
  import 'tinymce/plugins/template';
  import 'tinymce/plugins/textpattern';
  import 'tinymce/plugins/visualblocks';
  import 'tinymce/plugins/visualchars';
  import 'tinymce/plugins/wordcount';
  import '/public/resource/tinymce/indent2em/plugin.min.js';

  import {
    defineComponent,
    computed,
    nextTick,
    ref,
    unref,
    watch,
    onDeactivated,
    onBeforeUnmount,
    onMounted,
  } from 'vue';
  import ImgUpload from './ImgUpload.vue';
  import { toolbar, plugins } from './tinymce';
  import { buildShortUUID } from '/@/utils/uuid';
  import { bindHandlers } from './helper';
  import { onMountedOrActivated } from '/@/hooks/core/onMountedOrActivated';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { isNumber } from '/@/utils/is';
  import { useLocale } from '/@/locales/useLocale';
  import { useAppStore } from '/@/store/modules/app';
  import { getParamValues } from '/@/api/platform/paramValue';

  import { useGlobSetting } from '/@/hooks/setting';
  import { getImageFileApi, getFileApi } from '/@/api/platform/file';

  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  const tinymceProps = {
    options: {
      type: Object as PropType<Partial<RawEditorSettings>>,
      default: {},
    },
    value: {
      type: String,
    },
    toolbar: {
      type: Array as PropType<string[]>,
      default: toolbar,
    },
    plugins: {
      type: Array as PropType<string[]>,
      default: plugins,
    },
    modelValue: {
      type: String,
    },
    height: {
      type: [Number, String] as PropType<string | number>,
      required: false,
      default: 400,
    },
    width: {
      type: [Number, String] as PropType<string | number>,
      required: false,
      default: 'auto',
    },
    showImageUpload: {
      type: Boolean,
      default: true,
    },
    contentStyles: {},
  };

  export default defineComponent({
    name: 'Tinymce',
    components: { ImgUpload },
    inheritAttrs: false,
    props: tinymceProps,
    emits: ['change', 'update:modelValue', 'inited', 'init-error', 'fileUploadSuccess'],
    setup(props, { emit, attrs }) {
      console.log('src\\components\\Tinymce\\src\\Editor.vue fileUploadParams', props);

      const editorRef = ref<Nullable<Editor>>(null);
      const fullscreen = ref(false);
      const tinymceId = ref<string>(buildShortUUID('tiny-vue'));
      const elRef = ref<Nullable<HTMLElement>>(null);
      const imgStyles = ref({});
      const { uploadUrl } = useGlobSetting();
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getImageFileApi);
      const getVideoFileUrlPrefix = ref<string>(uploadUrl + getFileApi);
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      const { prefixCls } = useDesign('tinymce-container');

      const appStore = useAppStore();

      const tinymceContent = computed(() => props.modelValue);

      const containerWidth = computed(() => {
        const width = props.width;
        if (isNumber(width)) {
          return `${width}px`;
        }
        return width;
      });

      const skinName = computed(() => {
        return appStore.getDarkMode === 'light' ? 'oxide' : 'oxide-dark';
      });

      const langName = computed(() => {
        const lang = useLocale().getLocale.value;
        return ['zh_CN', 'en'].includes(lang) ? lang : 'zh_CN';
      });

      const initOptions = computed((): RawEditorSettings => {
        const { height, options, toolbar, plugins } = props;
        const publicPath = import.meta.env.VITE_PUBLIC_PATH || '/';
        //2023-7-17,build后得到的引用js和css路径错误，VITE_PUBLIC_PATH重复2次，在此去掉
        return {
          selector: `#${unref(tinymceId)}`,
          height,
          toolbar,
          menubar: 'file edit insert view format table',
          plugins,
          //设置粘贴paste插件的事件和属性
          // paste_preprocess: function (plugin, args) {
          //   console.log('paste_preprocess', args.content);
          //   //2023-10-22，渠成科技修改
          //   //针对粘贴excel或其他来源最终在编辑器中得到table进行边框处理
          //   //边框处理方法：对table、th、td均去掉border样式，再重新添加有边框的border样式
          //   let pasteContent = args.content;
          //   if (pasteContent != undefined && pasteContent != null && pasteContent.length > 0x0) {
          //     //每一个table节点的处理
          //     //1.去除节点的边框样式为空的内容:el.style.removeProperty("border")
          //     //2.对table添加边框样式属性:el.style.setProperty("border", "2px solid black")
          //     const pasteContentHtml = new DOMParser().parseFromString(pasteContent, 'text/html');
          //     console.log('pasteContentHtml.body', pasteContentHtml.body);
          //     //按TagName为table获取元素
          //     let tables = pasteContentHtml.body.getElementsByTagName('table');
          //     console.log('pasteContentHtml.body table', tables);
          //     if (tables != undefined && tables != null && tables.length > 0x0) {
          //       for (let i = 0; i < tables.length; i++) {
          //         const tableElement = tables[i];
          //         //每一个table节点的处理
          //         //1.去除节点的边框样式为空的内容:el.style.removeProperty("border")
          //         //2.对table添加边框样式属性:el.style.setProperty("border", "2px solid black")
          //         tableElement.style.removeProperty('border');
          //         tableElement.style.removeProperty('border-left');
          //         tableElement.style.removeProperty('border-right');
          //         tableElement.style.removeProperty('border-top');
          //         tableElement.style.removeProperty('border-bottom');
          //         tableElement.style.setProperty('border', '2px solid black');

          //         //获取表格中的th元素，按TagName为th获取元素
          //         let ths = tableElement.getElementsByTagName('th');
          //         if (ths != undefined && ths != null && ths.length > 0x0) {
          //           for (let j = 0; j < ths.length; j++) {
          //             const thElement = ths[j];
          //             thElement.style.removeProperty('border');
          //             thElement.style.removeProperty('border-left');
          //             thElement.style.removeProperty('border-right');
          //             thElement.style.removeProperty('border-top');
          //             thElement.style.removeProperty('border-bottom');
          //             thElement.style.setProperty('border', '1px solid black');
          //           }
          //         }
          //         //按TagName为td获取元素
          //         let tds = tableElement.getElementsByTagName('td');
          //         if (tds != undefined && tds != null && tds.length > 0x0) {
          //           for (let i = 0; i < tds.length; i++) {
          //             const tdElement = tds[i];
          //             tdElement.style.removeProperty('border');
          //             tdElement.style.removeProperty('border-left');
          //             tdElement.style.removeProperty('border-right');
          //             tdElement.style.removeProperty('border-top');
          //             tdElement.style.removeProperty('border-bottom');
          //             tdElement.style.setProperty('border', '1px solid black');
          //           }
          //         }
          //       }
          //       args.content = pasteContentHtml.body.innerHTML;
          //     }
          //   }
          // },
          // paste_postprocess: function (plugin, args) {
          //   console.log('paste_postprocess', args.node);
          // },
          //是否粘贴为纯文本
          // paste_as_text: true,
          paste_retain_style_properties:
            'color background text-align font-size font-family border border-top border-bottom border-left border-right',
          // paste_retain_style_properties: 'color background  border',
          //添加扩展插件powerpaste
          external_plugins: {
            powerpaste: 'resource/tinymce/powerpaste/plugin.min.js',
            // powerpaste: '/@/../resource/tinymce/powerpaste/plugin.min.js',//使用@路径引入报错，导致插件无法使用；PowerPaste is incompatible with Paste plugin! Remove 'paste' from the 'plugins' option.
          },
          powerpaste_word_import: 'propmt', // 参数可以是propmt, merge, clear，效果自行切换对比
          powerpaste_html_import: 'propmt', // propmt, merge, clear
          powerpaste_allow_local_images: false,
          // language_url: publicPath + 'resource/tinymce/langs/' + langName.value + '.js',
          language_url: 'resource/tinymce/langs/' + langName.value + '.js',
          language: langName.value,
          branding: false,
          default_link_target: '_blank',
          link_title: false,
          object_resizing: false,
          auto_focus: true,
          skin: skinName.value,
          // skin_url: publicPath + 'resource/tinymce/skins/ui/' + skinName.value,
          skin_url: 'resource/tinymce/skins/ui/' + skinName.value,
          content_css:
            //实测在dev环境下需要使用publicPath，不加publicPath时css提示404
            // publicPath + 'resource/tinymce/skins/ui/' + skinName.value + '/content.min.css',
            'resource/tinymce/skins/ui/' + skinName.value + '/content.min.css',
          // 'resource/tinymce/skins/ui/' + skinName.value + '/content.min.css',
          ...options,
          setup: (editor: Editor) => {
            editorRef.value = editor;
            editor.on('init', (e) => initSetup(e));
          },
        };
      });

      const disabled = computed(() => {
        const { options } = props;
        const getdDisabled = options && Reflect.get(options, 'readonly');
        const editor = unref(editorRef);
        if (editor) {
          editor.setMode(getdDisabled ? 'readonly' : 'design');
        }
        return getdDisabled ?? false;
      });

      watch(
        () => attrs.disabled,
        () => {
          const editor = unref(editorRef);
          if (!editor) {
            return;
          }
          editor.setMode(attrs.disabled ? 'readonly' : 'design');
        },
      );

      onMountedOrActivated(() => {
        if (!initOptions.value.inline) {
          tinymceId.value = buildShortUUID('tiny-vue');
        }
        nextTick(() => {
          setTimeout(() => {
            initEditor();
          }, 30);
        });
      });

      onBeforeUnmount(() => {
        destory();
      });

      onDeactivated(() => {
        destory();
      });

      function destory() {
        if (tinymce !== null) {
          tinymce?.remove?.(unref(initOptions).selector!);
        }
      }

      function initEditor() {
        const el = unref(elRef);
        if (el) {
          el.style.visibility = '';
        }
        tinymce
          .init(unref(initOptions))
          .then((editor) => {
            emit('inited', editor);
          })
          .catch((err) => {
            emit('init-error', err);
          });
      }

      function initSetup(e) {
        const editor = unref(editorRef);
        if (!editor) {
          return;
        }
        const value = props.modelValue || '';

        editor.setContent(value);
        bindModelHandlers(editor);
        bindHandlers(e, attrs, unref(editorRef));
      }

      function setValue(editor: Recordable, val: string, prevVal?: string) {
        if (
          editor &&
          typeof val === 'string' &&
          val !== prevVal &&
          val !== editor.getContent({ format: attrs.outputFormat })
        ) {
          editor.setContent(val);
        }
      }

      /**
       * 设置cms文章内容固定格式：从项目参数配置节点中获取样式
       */
      async function setCmsAarticleFormat() {
        const editor = unref(editorRef);
        if (!editor) {
          return;
        }
        const { contentStyles } = props;
        if (!contentStyles || Object.keys(contentStyles).length < 0x1) {
          return;
        }
        // console.log('父组件传递数据', contentStyles);
        let p_html = tinymce.activeEditor.dom.select('p');
        let div_html = tinymce.activeEditor.dom.select('div');
        if (p_html.length > 0x0) {
          await tinymce.activeEditor.dom.setStyles(p_html, contentStyles);
          const content = editor.getContent({ format: attrs.outputFormat });
          emit('update:modelValue', content);
          emit('change', content);
        }
        if (div_html.length > 0x0) {
          await tinymce.activeEditor.dom.setStyles(div_html, contentStyles);
          const content = editor.getContent({ format: attrs.outputFormat });
          emit('update:modelValue', content);
          emit('change', content);
        }
        createMessage.success('设置首行缩进、行高、加粗格式成功！', 3);
      }

      function bindModelHandlers(editor: any) {
        const modelEvents = attrs.modelEvents ? attrs.modelEvents : null;
        const normalizedEvents = Array.isArray(modelEvents) ? modelEvents.join(' ') : modelEvents;

        watch(
          () => props.modelValue,
          (val: string, prevVal: string) => {
            setValue(editor, val, prevVal);
          },
        );

        watch(
          () => props.value,
          (val: string, prevVal: string) => {
            setValue(editor, val, prevVal);
          },
          {
            immediate: true,
          },
        );

        editor.on(normalizedEvents ? normalizedEvents : 'change keyup undo redo', () => {
          const content = editor.getContent({ format: attrs.outputFormat });
          emit('update:modelValue', content);
          emit('change', content);
        });

        editor.on('FullscreenStateChanged', (e) => {
          fullscreen.value = e.state;
        });
      }

      function handleImageUploading(name: string) {
        const editor = unref(editorRef);
        if (!editor) {
          return;
        }
        editor.execCommand('mceInsertContent', false, getUploadingImgName(name));
        const content = editor?.getContent() ?? '';
        setValue(editor, content);
      }

      async function getImgStyles() {
        getParamValues({
          tablecode: 'qc_project',
          objectids: projectCode.value,
          paramnodes: 'cms>editor>img>*',
        })
          .then((res) => {
            if (!res || Object.keys(res).length > 0x0) {
              for (let i = 0; i < res.length; i++) {
                let values = res[i].values;
                if (!values || Object.keys(values).length > 0x0) {
                  imgStyles.value = res[i].values;
                }
              }
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      function handleDone(name: string, fileid: string, type: string) {
        console.log(
          'src\\components\\Tinymce\\src\\Editor.vue handleDone name=' +
            name +
            ' fileid=' +
            fileid +
            ' type=' +
            type,
        );
        const editor = unref(editorRef);
        if (!editor) {
          return;
        }
        const content = editor?.getContent() ?? '';
        const val =
          content?.replace(
            getUploadingImgName(name),
            type == 'video/mp4'
              ? '<div style="display: flex; align-items: center; justify-content: center;"><video controls="controls" autoplay="autoplay" width = "600px"><source src="' +
                  `${getVideoFileUrlPrefix.value + fileid}` +
                  '" /> </video></div>'
              : `<img style="display: block; margin-left: auto; margin-right: auto;height:${
                  imgStyles.value?.height ?? 'auto'
                };width:${imgStyles.value?.width ?? '600px'}"  src= "${
                  getImageFileUrlPrefix.value + fileid
                }" />`,
          ) ?? '';
        setValue(editor, val);
        //测试触发在父组件中定义的事件，在父组件页面中调用事件得到上传的文件信息
        //如果文件类型是图片才进行父组件事件触发
        if (
          type == 'image/jpeg' ||
          type == 'image/jpg' ||
          type == 'image/png' ||
          type == 'image/bmp' ||
          type == 'image/gif' ||
          type == 'image/webp'
        ) {
          emit('fileUploadSuccess', { name: name, fileid: fileid, type: type });
        }
      }

      function getUploadingImgName(name: string) {
        return `[uploading:${name}]`;
      }

      onMounted(() => {
        getImgStyles();
      });

      return {
        prefixCls,
        containerWidth,
        initOptions,
        tinymceContent,
        elRef,
        tinymceId,
        handleImageUploading,
        handleDone,
        getImageFileUrlPrefix,
        getVideoFileUrlPrefix,
        editorRef,
        fullscreen,
        disabled,
        setCmsAarticleFormat,
      };
    },
  });
</script>

<style lang="less" scoped></style>

<style lang="less">
  @prefix-cls: ~'@{namespace}-tinymce-container';

  .@{prefix-cls} {
    position: relative;
    line-height: normal;

    textarea {
      z-index: -1;
      visibility: hidden;
    }
  }
</style>
